"""
历史分析选品工作线程
"""
from PyQt6.QtCore import QThread, pyqtSignal
from biz.history_analysis_auto_select_commodity import HistoryAnalysisAutoSelectCommodity

class HistoryAnalysisAutoSelectWorker(QThread):
    """历史分析选品工作线程"""
    finished = pyqtSignal()
    error = pyqtSignal(str)
    log = pyqtSignal(str)  # 声明为 str 类型
    progress = pyqtSignal(int, int)  # 当前进度, 总数
    result = pyqtSignal(list)
    stopped = pyqtSignal()  # 添加停止信号

    def __init__(self, params):
        super().__init__()
        self.params = params
        self.analyzer = HistoryAnalysisAutoSelectCommodity()
        # 连接信号
        self.analyzer.log_signal.connect(lambda msg: self.log.emit(str(msg)))  # 确保转换为 str
        self.analyzer.progress_signal.connect(self.progress.emit)
        self.analyzer.result_signal.connect(self.result.emit)
        self.is_running = False

    def stop(self):
        """停止选品"""
        if self.analyzer:
            self.analyzer.stop()
        self.is_running = False
        self.stopped.emit()  # 发送停止信号

    def run(self):
        """执行选品"""
        try:
            self.is_running = True
            self.analyzer.select_commodities(
                min_price=self.params['price_min'],
                max_price=self.params['price_max'],
                min_sales=self.params['sales_min']
            )
            if self.is_running:  # 只有在正常完成时才发送finished信号
                self.finished.emit()
        except Exception as e:
            if self.is_running:  # 只有在正常运行时才发送error信号
                self.error.emit(str(e))
        finally:
            self.is_running = False
